package com.project.collectAPI.comm;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.Serializable;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class WeChat implements Serializable{

     private static final long serialVersionUID = 1L;

    //公众号Appid
    public static String AppID="wx896ca5a457ec03f6";
    //公众号AppSecret
    public static String AppSecret="5a17bfaa2b6933532f795ea7bb9cc7c7";


    //获取token
    public static String getToken(){
        String reqUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+AppID+"&secret="+AppSecret;
        String res=HttpGet(reqUrl);
        if(!StringUtils.isEmpty(res)){
            JSONObject json=JSONObject.parseObject(res);
            if(!Objects.isNull(json)){
                return json.getString("access_token").toString();
            }
        }
        return null;
    }

    public static String getOpenid(String wxLoginCode){
        String httpUrl="https://api.weixin.qq.com/sns/jscode2session";
        StringBuffer httpArg = new StringBuffer();
        httpArg.append(httpUrl).append("?");
        httpArg.append("appid=").append(AppID).append("&");
        httpArg.append("secret=").append(AppSecret).append("&");
        httpArg.append("js_code=").append(wxLoginCode).append("&");
        httpArg.append("grant_type=").append("authorization_code");
        System.out.println("httpArg请求参数:"+httpArg);
        String result = HttpGet(httpArg.toString());
        System.out.println(result);
        return result;
    }



    /* 微信api */
    /*下发统一消息*/
    /*public static void sendUniformMessage(String accessToken){
        String httpUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/uniform_send?access_token="+accessToken;
        *//*List params=new ArrayList();
        params.add(new BasicNameValuePair("touser","obol15E5sxeKYl0X7BbXQzFXWKjw"));*//*

        //Post参数
        JSONObject json=new JSONObject();
        json.put("touser","obol15E5sxeKYl0X7BbXQzFXWKjw");

        //公众号模板消息参数
        JSONObject mp_template_msg=new JSONObject();
        mp_template_msg.put("template_id","ROw7br4KEU021ZDZFvA7fr7Iz9z8GlsAR96Ec42dPik"); //小程序模板ID
        mp_template_msg.put("page","page/page/index"); //小程序页面路径
        mp_template_msg.put("form_id","page/page/index"); //小程序模板消息formid
        json.put("mp_template_msg",mp_template_msg); //使用公众号消息模板


        String result = HttpPostJson(httpUrl,json); //HttpJson请求
        System.out.println(result);
    }*/













    public static String HttpGet(String url){
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数

        CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);//返回请求执行结果
            int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //System.out.println("服务器响应:===>:"+result);
                return result;
            }
        } catch (Exception e) {
            System.out.println(("httpget Exception handle-- > " + e));
        } finally {
            if (response != null){
                try {
                    response.close();//关闭response
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
            if(httpclient != null){
                try {
                    httpclient.close();//关闭httpclient
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
        }
        return null;
    }





    public static String HttpGet(String url,String AuthStr){
        //单位毫秒
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(3000).setConnectTimeout(3000)
                .setSocketTimeout(3000).build();//设置请求的状态参数

        CloseableHttpClient httpclient = HttpClients.createDefault();//创建 CloseableHttpClient
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(requestConfig);
        httpGet.setHeader("Authorization",AuthStr);
        httpGet.setHeader("Accept","application/json");
        httpGet.setHeader("User-Agent","https://zh.wikipedia.org/wiki/User_agent");

        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);//返回请求执行结果
            int statusCode = response.getStatusLine().getStatusCode();//获取返回的状态值
            if (statusCode != HttpStatus.SC_OK) {
                return null;
            } else {
                String result = EntityUtils.toString(response.getEntity(), "UTF-8");
                //System.out.println("服务器响应:===>:"+result);
                return result;
            }
        } catch (Exception e) {
            System.out.println(("httpget Exception handle-- > " + e));
        } finally {
            if (response != null){
                try {
                    response.close();//关闭response
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
            if(httpclient != null){
                try {
                    httpclient.close();//关闭httpclient
                } catch (IOException e) {
                    System.out.println(("httpget IOException handle-- > " + e));
                }
            }
        }
        return null;
    }






    /*
    *  表单 HttpPost请求
    *  List params=new ArrayList();
    *  //添加参数
    *  params.add(new BasicNameValuePair("键","值"));
    * */
    public static String HttpPost(String url,List<NameValuePair> nameValues){
        //创建Http Post请求
        //HttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            //httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));
            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     * json HttpPost请求
     * */
    public static String HttpPostJson(String url,JSONObject json){
        //创建Http Post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json.toString(), StandardCharsets.UTF_8));
            httpPost.setHeader("accept","*/*");
            httpPost.setHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpPost.setHeader("Content-type", "application/json"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /*
     * json HttpPost请求
     * */
    public static String HttpPostJson(String url,JSONObject json,String AuthorizationStr){
        System.out.println("签名信息========>"+AuthorizationStr);
        //创建Http Post请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            httpPost.setEntity(new StringEntity(json.toString(), StandardCharsets.UTF_8));
            httpPost.setHeader("Authorization",AuthorizationStr);
            httpPost.setHeader("accept","*/*");
            httpPost.setHeader("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            httpPost.setHeader("Content-type", "application/json"); //application/x-www-form-urlencoded  application/json
            HttpResponse response = httpClient.execute(httpPost);
            String jsonData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+jsonData);
            if (!StringUtils.isEmpty(jsonData)) {
                return JSON.parseObject(jsonData).toJSONString();
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    //ntpost.setEntity(new StringEntity(xml))
    /*
     *  表单 HttpPost请求 XML
     *  List params=new ArrayList();
     *  //添加参数
     *  params.add(new BasicNameValuePair("键","值"));
     * */
    public static Map<String,Object> HttpPostXML(String url, String xmlString){
        //创建Http Post请求
        //HttpClient httpClient = HttpClientBuilder.create().build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost;
        try {
            //准备开始请求
            httpPost = new HttpPost(url);
            //httpPost.setEntity(new UrlEncodedFormEntity(nameValues, StandardCharsets.UTF_8));

            httpPost.setHeader("Content-type", "text/xml;charset=UTF-8"); //application/x-www-form-urlencoded  application/json
            //解决中文乱码问题
            StringEntity stringEntity = new StringEntity(xmlString,"UTF-8");
            stringEntity.setContentEncoding("UTF-8");
            httpPost.setEntity(stringEntity);

            HttpResponse response = httpClient.execute(httpPost);
            String xmlData= EntityUtils.toString(response.getEntity());
            System.out.println("对方服务器返回结果:"+xmlData);
            if (!StringUtils.isEmpty(xmlData)) {
                System.out.println(XmlReader.xmlToMap(xmlData));
                return XmlReader.xmlToMap(xmlData);
            }
        }
        catch (SocketException e) {
            System.out.println("错误=>:" +e.getMessage().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
